import subprocess as sp
import cv2
import sys
import queue
import threading
import numpy as np

class PushStream(object):
    def __init__(self,rtmpUrl="rtsp://192.168.12.20:554/7",fps=30,width=640,height=480) -> None:
        self.frame_queue = queue.Queue()
        self.rtmpUrl = rtmpUrl


        #获取摄像头参数

        self.fps = fps
        self.width = width
        self.height = height


        self.command = ['ffmpeg',
           '-y',
           '-f', 'rawvideo',
           '-vcodec', 'rawvideo',
           '-pix_fmt', 'bgr24',
           '-s', "{}x{}".format(self.width,self.height),
           '-i', '-',
           '-c:v', 'libx264',
           '-preset', 'ultrafast',
           '-f', 'rtsp',
            self.rtmpUrl]
    
    #读流函数           
    def video(self,frame=None):
        if frame is not None:
            self.frame_queue.put(frame)
        else:
            self.frame_queue.put(np.zeros(self.width,self.height,3))


    def push_stream(self):
        # 管道配置
        while True:
            if len(self.command)>0:
                p = sp.Popen(self.command, stdin=sp.PIPE,bufsize=10**8)
                break

        while True:
            if not self.frame_queue.empty():
                frame = self.frame_queue.get()
                if frame is not None:
                    frame = cv2.resize(frame, (self.width, self.height))
                    p.stdin.write(frame.tobytes())
    
                                

    def run(self):
        # thread_video = threading.Thread(target=self.video,)
        thread_push = threading.Thread(target=self.push_stream,)
        # thread_video.start()
        thread_push.start()


if __name__ == "__main__":
    pusher=PushStream()
    cap=cv2.VideoCapture(0)
    
    pusher.run()
    while True:
        ret,frame=cap.read()
        print(frame)
        pusher.video(frame)
        
    
